<?php
class Entity_Model {
    
    private $valueMap;
    private $tableName;
    private $primaryKeyList;
    private $fieldNames;
    protected $hasCreationFields = true;
    protected $hasModificationFields = true;
    protected $hasEntityVersion = true;
    
    public function __construct($tableName, $ownFieldNames, $primaryKeyList, $valueMap, $fieldNameSubstitutionMap = null) {
        $this->fieldNames = array_merge(
                $ownFieldNames,
                array(
                    'entity_version',
                    'created_by_id',
                    'created_at',
                    'modified_by_id',
                    'modified_at'
                )
        );
        
        $this->valueMap = $this->filterValueMap($valueMap, $fieldNameSubstitutionMap);
        
        $this->tableName = $tableName;
        if (! is_array($primaryKeyList)) {
            $primaryKeyList = array($primaryKeyList);
        }
        $this->primaryKeyList = $primaryKeyList;
    }
    
    protected function filterValueMap($valueMap, $fieldNameSubstitutionMap) {
        if ($fieldNameSubstitutionMap) {
            foreach ($fieldNameSubstitutionMap as $key => $replaceBy) {
                if (! array_key_exists($replaceBy, $valueMap) && array_key_exists($key, $valueMap)) {
                    $valueMap[$replaceBy] = $valueMap[$key];
                }
            }
        }
        return arrays::filterMap($valueMap, $this->fieldNames);
    }
    
    public function getFieldNames() {
        return $this->ownFieldNames;
    }
    
    public function getMap() {
        return $this->valueMap;
    }
    
    public function getTableName() {
        return $this->tableName;
    }
    
    public function getPrimaryKeyList() {
        return $this->primaryKeyList;
    }
    
    public function get($fieldName) {
        return $this->valueMap[$fieldName];
    }
    
    public function isPersistent() {
        return sql::isPersistent($this->valueMap);
    }
    
    public function getPkValues() {
        return arrays::filterMap($this->valueMap, $this->primaryKeyList);
    }
    
    public function hasCreationFields() {
    	return $this->hasCreationFields;
    }
    
    public function hasModificationFields() {
    	return $this->hasModificationFields;
    }
    
    public function hasEntityVersion() {
    	return $this->hasEntityVersion;
    }
}